package config

import (
	"os"
	"sync"

	"github.com/go-playground/validator"
	"github.com/kelseyhightower/envconfig"
	"github.com/mcuadros/go-defaults"
	"github.com/sirupsen/logrus"
)

var (
	e       = &Env{}
	envOnce sync.Once
)

type Env struct {
	SpEntry                      string `envconfig:"SPENTRY" validate:"required"`
	SpPort                       string `envconfig:"SP_PORT" default:"7000"`
	SpUserIdHeaderField          string `envconfig:"SP_USER_ID_HEADER_FIELD" default:"x-sp-user-id"`
	SpUserSignatureHeaderField   string `envconfig:"SP_USER_SIGNATURE_HEADER_FIELD" default:"x-sp-signature"`
	SpUserSignVersionHeaderField string `envconfig:"SP_USER_SIGN_VERSION_HEADER_FIELD" default:"x-sp-sign-version"`
	SpLogkitUri                  string `envconfig:"SP_LOGKIT_URI"`
	SpLogkitNamespace            string `envconfig:"SP_LOGKIT_NAMESPACE" default:"/logkit"`
	SpLogkitPath                 string `envconfig:"SP_LOGKIT_PATH"`
	SpLogkitEventsAppend         string `envconfig:"SP_LOGKIT_EVENTS_APPEND" default:"append"`
	SpLogkitLogsLevel            string `envconfig:"SP_LOGKIT_LOGS_LEVEL" default:"info"`
	K8SPodName                   string `envconfig:"HOSTNAME" default:"sh-solver"`
	ShSolverServiceEndpoint      string `envconfig:"SH_SOLVER_SERVICE_ENDPOINT" validate:"required"`
	OssType                      string `envconfig:"OSS_TYPE" validate:"required"`
	OssEndpoint                  string `envconfig:"OSS_ENDPOINT" validate:"required"`
	OssBucket                    string `envconfig:"OSS_BUCKET" validate:"required"`
	OssAccessKey                 string `envconfig:"OSS_ACCESS_KEY" validate:"required"`
	OssAccessSecret              string `envconfig:"OSS_ACCESS_SECRET" validate:"required"`
	ResultPath                   string `envconfig:"RESULT_PATH"`
	ResultOSSPath                string `envconfig:"RESULT_OSS_PATH"`
}

func init() {
	//debug level
	//logrus.SetLevel(logrus.DebugLevel)
	logrus.SetLevel(logrus.InfoLevel)
	logrus.SetReportCaller(true)
	logrus.SetFormatter(&logrus.TextFormatter{
		DisableColors:   false,
		TimestampFormat: "2006-01-02 15:03:04",
	})
}

// because of env config was inhired in system env, system env setting was binding to kubernetes pod
// so no need to update the config until pod restart
func GetEnv() *Env {
	envOnce.Do(func() {
		e = buildEnv()
	})

	return e
}

func buildEnv() *Env {
	err := envconfig.Process("config", e)
	if err != nil {
		logrus.Errorf("Decode env variables failed: %s", err.Error())
	}

	defaults.SetDefaults(e)
	entry := os.Getenv("spentry")
	if entry == "" {
		entry = "sh"
	}

	e.SpEntry = entry
	validate := validator.New()
	err = validate.Struct(e)
	if err != nil {
		logrus.Errorf("Validate env variables failed: %s", err.Error())
	}

	return e
}
